/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tcc.ejb.controleProjeto.controle;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import tcc.ejb.controleProjeto.controle.exceptions.IllegalOrphanException;
import tcc.ejb.controleProjeto.controle.exceptions.NonexistentEntityException;
import tcc.ejb.controleProjeto.controle.exceptions.PreexistingEntityException;
import tcc.ejb.controleProjeto.entidade.Projeto;
import tcc.ejb.controleProjeto.entidade.Release;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Maciel
 */
public class ProjetoJpaController {

    public ProjetoJpaController() {
        emf = Persistence.createEntityManagerFactory("WebApplication4PU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Projeto projeto) throws PreexistingEntityException, Exception {
        if (projeto.getReleaseList() == null) {
            projeto.setReleaseList(new ArrayList<Release>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Release> attachedReleaseList = new ArrayList<Release>();
            for (Release releaseListReleaseToAttach : projeto.getReleaseList()) {
                releaseListReleaseToAttach = em.getReference(releaseListReleaseToAttach.getClass(), releaseListReleaseToAttach.getId());
                attachedReleaseList.add(releaseListReleaseToAttach);
            }
            projeto.setReleaseList(attachedReleaseList);
            em.persist(projeto);
            for (Release releaseListRelease : projeto.getReleaseList()) {
                Projeto oldProjetoOfReleaseListRelease = releaseListRelease.getProjeto();
                releaseListRelease.setProjeto(projeto);
                releaseListRelease = em.merge(releaseListRelease);
                if (oldProjetoOfReleaseListRelease != null) {
                    oldProjetoOfReleaseListRelease.getReleaseList().remove(releaseListRelease);
                    oldProjetoOfReleaseListRelease = em.merge(oldProjetoOfReleaseListRelease);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findProjeto(projeto.getId()) != null) {
                throw new PreexistingEntityException("Projeto " + projeto + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Projeto projeto) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Projeto persistentProjeto = em.find(Projeto.class, projeto.getId());
            List<Release> releaseListOld = persistentProjeto.getReleaseList();
            List<Release> releaseListNew = projeto.getReleaseList();
            List<String> illegalOrphanMessages = null;
            for (Release releaseListOldRelease : releaseListOld) {
                if (!releaseListNew.contains(releaseListOldRelease)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Release " + releaseListOldRelease + " since its projeto field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Release> attachedReleaseListNew = new ArrayList<Release>();
            for (Release releaseListNewReleaseToAttach : releaseListNew) {
                releaseListNewReleaseToAttach = em.getReference(releaseListNewReleaseToAttach.getClass(), releaseListNewReleaseToAttach.getId());
                attachedReleaseListNew.add(releaseListNewReleaseToAttach);
            }
            releaseListNew = attachedReleaseListNew;
            projeto.setReleaseList(releaseListNew);
            projeto = em.merge(projeto);
            for (Release releaseListNewRelease : releaseListNew) {
                if (!releaseListOld.contains(releaseListNewRelease)) {
                    Projeto oldProjetoOfReleaseListNewRelease = releaseListNewRelease.getProjeto();
                    releaseListNewRelease.setProjeto(projeto);
                    releaseListNewRelease = em.merge(releaseListNewRelease);
                    if (oldProjetoOfReleaseListNewRelease != null && !oldProjetoOfReleaseListNewRelease.equals(projeto)) {
                        oldProjetoOfReleaseListNewRelease.getReleaseList().remove(releaseListNewRelease);
                        oldProjetoOfReleaseListNewRelease = em.merge(oldProjetoOfReleaseListNewRelease);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = projeto.getId();
                if (findProjeto(id) == null) {
                    throw new NonexistentEntityException("The projeto with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Projeto projeto;
            try {
                projeto = em.getReference(Projeto.class, id);
                projeto.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The projeto with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Release> releaseListOrphanCheck = projeto.getReleaseList();
            for (Release releaseListOrphanCheckRelease : releaseListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Projeto (" + projeto + ") cannot be destroyed since the Release " + releaseListOrphanCheckRelease + " in its releaseList field has a non-nullable projeto field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(projeto);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Projeto> findProjetoEntities() {
        return findProjetoEntities(true, -1, -1);
    }

    public List<Projeto> findProjetoEntities(int maxResults, int firstResult) {
        return findProjetoEntities(false, maxResults, firstResult);
    }

    private List<Projeto> findProjetoEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Projeto.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Projeto findProjeto(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Projeto.class, id);
        } finally {
            em.close();
        }
    }

    public int getProjetoCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Projeto> rt = cq.from(Projeto.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
